// kvStoreManager.ts
import distributedData from '@ohos.data.distributedData';

let kvStore: distributedData.SingleKVStore | null = null;

// 初始化kvStore
export async function initKVStore(): Promise<void> {
  try {
    // 创建KVManager时，确保传递正确的参数
    const kvManager = await distributedData.createKVManager({
      bundleName: '你的应用包名',  // 替换为你实际的应用包名
      userInfo: {
        userId: '0',
        userType: distributedData.UserType.SAME_USER_ID
      }
    });

    // 获取KVStore时，确保传递storeId，且不遗漏其他参数
    kvStore = await kvManager.getKVStore('demoStore', {
      createIfMissing: true,
      encrypt: false,
      backup: false,
      autoSync: true,
      kvStoreType: distributedData.KVStoreType.SINGLE_VERSION,
      securityLevel: distributedData.SecurityLevel.S1
    });

  } catch (error) {
    console.error('KVStore 初始化失败:', error);
  }
}

// 新增或修改key-value
export async function putValue(key: string, value: string): Promise<void> {
  if (!kvStore) {
    await initKVStore();
  }
  if (kvStore) {
    await kvStore.put(key, value);
  }
}

// 查询所有key-value
export async function queryAll(): Promise<Map<string, string>> {
  if (!kvStore) {
    await initKVStore();
  }
  const map = new Map<string, string>();
  if (kvStore) {
    const entries = await kvStore.getEntries('');
    entries.forEach((entry: { key: string; value: unknown }) => {
      if (typeof entry.value === 'string') {
        map.set(entry.key, entry.value);
      }
    });
  }
  return map;
}

// 删除某个key
export async function deleteKey(key: string): Promise<void> {
  if (!kvStore) {
    await initKVStore();
  }
  if (kvStore) {
    await kvStore.delete(key);
  }
}
